<template>
  <view class="edit-profile-container">
    <view class="header">
      <text class="title">编辑资料</text>
    </view>
    
    <view class="form-container">
      <!-- 头像上传 -->
      <view class="avatar-section">
        <view class="avatar-upload">
          <image 
            class="avatar-preview" 
            :src="formData.avatar || '/static/default-avatar.svg'" 
            mode="aspectFill"
          ></image>
          <view class="upload-overlay">
            <image class="upload-icon" src="/static/icons/camera.svg" mode="aspectFit"></image>
          </view>
          <input 
            type="file" 
            accept="image/*" 
            class="avatar-input" 
            @change="handleAvatarUpload"
            :disabled="uploading"
          />
        </view>
        <text class="avatar-hint">点击更换头像</text>
      </view>
      
      <!-- 表单输入 -->
      <view class="form-group">
        <view class="input-item">
          <image src="/static/icons/user.svg" class="input-icon" mode="aspectFit"></image>
          <text class="input-label">用户名</text>
          <input 
            type="text" 
            v-model="formData.username" 
            placeholder="用户名" 
            placeholder-style="color: #999"
            disabled
          />
        </view>
        
        <view class="input-item">
          <image src="/static/icons/email.svg" class="input-icon" mode="aspectFit"></image>
          <text class="input-label">邮箱</text>
          <input 
            type="text" 
            v-model="formData.email" 
            placeholder="请输入邮箱" 
            placeholder-style="color: #999"
            :disabled="uploading"
          />
        </view>
        
        <view class="input-item">
          <image src="/static/icons/info.svg" class="input-icon" mode="aspectFit"></image>
          <text class="input-label">个人简介</text>
          <textarea 
            v-model="formData.bio" 
            placeholder="介绍一下自己吧（最多500字）" 
            placeholder-style="color: #999"
            maxlength="500"
            rows="4"
            class="bio-textarea"
            :disabled="uploading"
          ></textarea>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button 
          class="btn-primary"
          @click="handleSubmit"
          :disabled="uploading"
        >
          {{ uploading ? '保存中...' : '保存修改' }}
        </button>
        <button 
          class="btn-secondary"
          @click="handleCancel"
          :disabled="uploading"
        >
          取消
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { updateUserInfo } from '@/utils/api'
import { getUserInfo, setUserInfo } from '@/utils/auth'

export default {
  data() {
    return {
      formData: {
        username: '',
        email: '',
        bio: '',
        avatar: ''
      },
      uploading: false
    }
  },
  onLoad() {
    this.loadUserInfo()
  },
  methods: {
    loadUserInfo() {
      const userInfo = getUserInfo()
      if (userInfo) {
        // 将JSON字符串转换为对象
        const userData = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
        this.formData = {
          username: userData.username || '',
          email: userData.email || '',
          bio: userData.bio || '',
          avatar: userData.avatar || ''
        }
      }
    },
    
    handleAvatarUpload(e) {
      const file = e.target.files[0]
      if (file) {
        // 检查文件大小（限制5MB）
        const maxSize = 5 * 1024 * 1024
        if (file.size > maxSize) {
          this.showToast('图片大小不能超过5MB', 'none')
          return
        }
        
        // 本地预览
        const reader = new FileReader()
        reader.onload = (event) => {
          this.formData.avatar = event.target.result
        }
        reader.readAsDataURL(file)
      }
    },
    
    async handleSubmit() {
      // 表单验证
      if (this.formData.email && !this.isValidEmail(this.formData.email)) {
        this.showToast('请输入有效的邮箱地址', 'none')
        return
      }
      
      this.uploading = true
      try {
        const updateData = {
          email: this.formData.email,
          bio: this.formData.bio,
          avatar: this.formData.avatar
        }
        
        // 调用API更新用户信息
        const updatedUser = await updateUserInfo(updateData)
        
        // 更新本地存储的用户信息
        setUserInfo(updatedUser)
        
        this.showToast('资料更新成功', 'success')
        
        // 延迟返回上一页，让用户看到成功提示
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (err) {
        this.showToast(err.message || '更新失败，请重试', 'none')
        console.error('更新用户信息失败:', err)
      } finally {
        this.uploading = false
      }
    },
    
    handleCancel() {
      // 检查是否有未保存的修改
      const hasChanges = this.hasUnsavedChanges()
      if (hasChanges) {
        uni.showModal({
          title: '确认取消',
          content: '您有未保存的修改，确定要离开吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    },
    
    // 检查是否有未保存的修改
    hasUnsavedChanges() {
      const originalUserInfo = getUserInfo()
      if (!originalUserInfo) return false
      
      const userData = typeof originalUserInfo === 'string' ? JSON.parse(originalUserInfo) : originalUserInfo
      
      return this.formData.email !== (userData.email || '') || 
             this.formData.bio !== (userData.bio || '') || 
             this.formData.avatar !== (userData.avatar || '')
    },
    
    showToast(title, icon = 'none') {
      uni.showToast({
        title,
        icon,
        duration: 2000
      })
    },
    
    isValidEmail(email) {
      const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return re.test(email);
    }
  }
}
</script>

<style scoped>
.edit-profile-container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  background-color: #fff;
  padding: 40rpx;
  text-align: center;
  border-bottom: 2rpx solid #f0f0f0;
  position: relative;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-container {
  padding: 30rpx 40rpx;
}

/* 头像上传样式 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
  padding: 40rpx 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.avatar-upload {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #f0f0f0;
}

.upload-overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 60rpx;
  height: 60rpx;
  background-color: #667eea;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 6rpx solid #fff;
}

.upload-icon {
  width: 36rpx;
  height: 36rpx;
  filter: invert(1);
}

.avatar-input {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.avatar-hint {
  font-size: 28rpx;
  color: #666;
}

/* 表单样式 */
.form-group {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 30rpx;
}

.input-item {
  display: flex;
  align-items: flex-start;
  padding: 30rpx 40rpx;
  border-bottom: 2rpx solid #f8f8f8;
}

.input-item:last-child {
  border-bottom: none;
}

.input-icon {
  width: 44rpx;
  height: 44rpx;
  margin-right: 30rpx;
  flex-shrink: 0;
}

.input-label {
  font-size: 32rpx;
  color: #666;
  width: 140rpx;
  flex-shrink: 0;
}

.input-item input {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  padding: 0;
}

.input-item input:disabled {
  color: #999;
}

.bio-textarea {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  padding: 0;
  height: 200rpx;
  line-height: 1.5;
}

/* 按钮样式 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-top: 40rpx;
}

.btn-primary {
  width: 100%;
  background-color: #667eea;
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  border-radius: 44rpx;
  padding: 32rpx 0;
  border: none;
  box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.btn-primary:active {
  background-color: #5a67d8;
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 10rpx rgba(102, 126, 234, 0.2);
}

.btn-primary:disabled {
  opacity: 0.7;
  transform: none;
  box-shadow: none;
}

.btn-secondary {
  width: 100%;
  background-color: #fff;
  color: #666;
  font-size: 36rpx;
  border-radius: 44rpx;
  padding: 32rpx 0;
  border: 2rpx solid #e0e0e0;
  transition: all 0.3s ease;
}

.btn-secondary:active {
  background-color: #f8f8f8;
  border-color: #d0d0d0;
  transform: translateY(2rpx);
}
</style>